import React, {Component} from "react";
import DropOption from "../../components/DropOption/DropOption";
import {isEmptyObj} from "../../utils/collectionUtils";

export default class DropMenuRender extends Component {
  constructor(props) {
    super(props);

    this.state = {
      headerName: props.colDef.headerName,
      actions: props.colDef.actions,
      record: props.data,
      menuClickHandler: props.context.menuClickHandler
    }
  }

  getMenuOps(actions){
    if(isEmptyObj(actions)){
      return null
    }

    let menuOpts = []
    actions.forEach(item => {
      menuOpts.push({key:item.actionId, name:item.name, subMenu: this.getMenuOps(item.subActions)})
    })

    return menuOpts
  }


  render() {
    return (
      <DropOption  onMenuClick={(e)=>{
        this.state.menuClickHandler(this.state.headerName, getCorrespondingRecord(this.state.headerName, this.state.record), e.key)
      }}
      menuOptions={this.getMenuOps(this.state.actions)} />
    );
  }
};

export const getCorrespondingRecord = (columnName, record) =>{
  if(isEmptyObj(record) || isEmptyObj(columnName)){
    return {}
  }

  if(columnName === 'Operation'){
    return record
  }

  return record[columnName]
}
